/*
 *  UIExpandingTextView.m
 *
 *  Created by Brandon Hamilton on 2011/05/03.
 *  Copyright 2011 Brandon Hamilton.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */

/*
 *  This class is based on growingTextView by Hans Pickaers
 *  http://www.hanspinckaers.com/multi-line-uitextview-similar-to-sms
 */

#import "UIExpandingTextView.h"
#import "UIUtil.h"

#define kTextInsetX 4
#define kTextInsetBottom 0

@implementation UIExpandingTextView

@synthesize internalTextView;
@synthesize delegate;

@synthesize text;
@synthesize font;
@synthesize textColor;
@synthesize textAlignment;
@synthesize selectedRange;
@synthesize editable;
@synthesize dataDetectorTypes;
@synthesize animateHeightChange;
@synthesize returnKeyType;
@synthesize textViewBackgroundImage;
@synthesize placeholder;
@synthesize textViewBackgroundImageName = _textViewBackgroundImageName;

- (void)setPlaceholder:(NSString *)placeholders
{
    placeholder = placeholders;
    placeholderLabel.text = placeholders;
}

- (int)minimumNumberOfLines
{
    return minimumNumberOfLines;
}

- (int)maximumNumberOfLines
{
    return maximumNumberOfLines;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        forceSizeUpdate = NO;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
        /* Internal Text View component */
		internalTextView = [[UIExpandingTextViewInternal alloc] init];
		internalTextView.delegate        = self;
		internalTextView.font            = [UIFont systemFontOfSize:18.0];
		internalTextView.scrollEnabled   = YES;
        internalTextView.opaque          = NO;
        internalTextView.backgroundColor = [UIColor clearColor];
        internalTextView.showsHorizontalScrollIndicator = NO;
        [internalTextView sizeToFit];
        internalTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
         internalTextView.layoutManager.allowsNonContiguousLayout = NO;
        
        /* set placeholder */
        placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(8,0,self.bounds.size.width - 16,self.bounds.size.height)];
        placeholderLabel.text = placeholder;
        placeholderLabel.font = Font14;
        placeholderLabel.backgroundColor = [UIColor clearColor];
        placeholderLabel.textColor = [UIColor grayColor];
        [internalTextView addSubview:placeholderLabel];
        
        /* Custom Background image */
        textViewBackgroundImage = [[UIImageView alloc] init];
        if (_textViewBackgroundImageName) {
            textViewBackgroundImage.image          = [[UIImage imageNamed:_textViewBackgroundImageName] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 30, 20, 30) resizingMode:UIImageResizingModeStretch];
            
        }else
        {
            textViewBackgroundImage.image          = [[UIImage imageNamed:@"chatviewtool_type.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 30, 20, 30) resizingMode:UIImageResizingModeStretch];
        }
        textViewBackgroundImage.contentMode    = UIViewContentModeScaleToFill;
        [self addSubview:textViewBackgroundImage];
        [self addSubview:internalTextView];
        
        /* Calculate the text view height */
		UIView *internal = (UIView*)[[internalTextView subviews] objectAtIndex:0];
		minimumHeight = internal.frame.size.height;
		[self setMinimumNumberOfLines:1];
		animateHeightChange = YES;
		internalTextView.text = @"";
		[self setMaximumNumberOfLines:4];
     
        self.frame = frame;
    }
    return self;
}
-(BOOL)becomeFirstResponder
{
    return [internalTextView becomeFirstResponder];
}

- (BOOL)isFirstResponder
{
    return [internalTextView isFirstResponder];
}
-(UITextView *)textBox
{
    return internalTextView;
}
-(void)sizeToFit
{
    CGRect r = self.frame;
    if ([self.text length] > 0)
    {
        /* No need to resize is text is not empty */
        return;
    }
    r.size.height = minimumHeight + kTextInsetBottom;
    self.frame = r;
}

-(void)setFrame:(CGRect)aframe
{
    CGRect backgroundFrame   = aframe;
    backgroundFrame.origin.y = 0;
    backgroundFrame.origin.x = 0;
    CGRect textViewFrame = CGRectInset(backgroundFrame, kTextInsetX, 4);
    textViewFrame.size.height -=4;
	internalTextView.frame   = textViewFrame;
    backgroundFrame.size.height  -= 8;
    textViewBackgroundImage.frame = backgroundFrame;
    forceSizeUpdate = YES;
	[super setFrame:aframe];
}

-(void)clearText
{
    self.text = @"";
//    [self textViewDidChange:self.internalTextView];
}

-(void)setMaximumNumberOfLines:(int)n
{
    
    CGSize textSize = [UIUtil textSizeWithFont:internalTextView.font width:MAXFLOAT height:MAXFLOAT text:@"计算一行文字的高度" lineBreakMode:NSLineBreakByCharWrapping];
    maximumHeight             = textSize.height * n;
    maximumNumberOfLines      = n;
}

-(void)setMinimumNumberOfLines:(int)m
{
    CGSize textSize = [UIUtil textSizeWithFont:internalTextView.font width:MAXFLOAT height:MAXFLOAT text:@"计算一行文字的高度" lineBreakMode:NSLineBreakByCharWrapping];
    minimumHeight             = textSize.height * m;
    minimumNumberOfLines = m;
}
- (void)textViewDidChange:(UITextView *)textView
{
    
    if(textView.text.length == 0)
        placeholderLabel.alpha = 1;
    else
        placeholderLabel.alpha = 0;
    
	CGFloat newHeight = internalTextView.contentSize.height;
    
    
	if(newHeight <= 44 || !internalTextView.hasText)
    {
        newHeight = 44;
    }
    int maximumHeight1 = 105;
	if (internalTextView.frame.size.height != newHeight || forceSizeUpdate)
	{
        forceSizeUpdate = NO;
        if (newHeight > maximumHeight)
        {
              newHeight = maximumHeight1;
        }
		if (newHeight <= maximumHeight1)
		{
            if ([delegate respondsToSelector:@selector(expandingTextView:willChangeHeight:)])
            {
                [delegate expandingTextView:self willChangeHeight:(newHeight+ kTextInsetBottom)];
            }
			
			/* Resize the frame */
			CGRect r = self.frame;
			r.size.height = newHeight + kTextInsetBottom;
			self.frame = r;
            
            if ([delegate respondsToSelector:@selector(expandingTextView:didChangeHeight:)])
            {
                [delegate expandingTextView:self didChangeHeight:(newHeight+ kTextInsetBottom)];
            }
		}
	}
	
	if ([delegate respondsToSelector:@selector(expandingTextViewDidChange:)])
    {
		[delegate expandingTextViewDidChange:self];
	}
    
	
}

-(void)growDidStop
{
	if ([delegate respondsToSelector:@selector(expandingTextView:didChangeHeight:)])
    {
		[delegate expandingTextView:self didChangeHeight:self.frame.size.height];
	}
}

-(BOOL)resignFirstResponder
{
	[super resignFirstResponder];
	return [internalTextView resignFirstResponder];
}

- (void)dealloc
{
	[internalTextView release];
    [textViewBackgroundImage release];
    [placeholderLabel release];
    [super dealloc];
}

#pragma mark UITextView properties

-(void)setText:(NSString *)atext
{
	internalTextView.text = atext;
//   [self.internalTextView setContentSize:[UIUtil textSizeWithFont:internalTextView.font width:self.frame.size.width height:MAXFLOAT text:self.internalTextView.text lineBreakMode:NSLineBreakByCharWrapping]];
    [internalTextView setContentSize:[internalTextView sizeThatFits:CGSizeMake(internalTextView.frame.size.width, MAXFLOAT)]];
    [self textViewDidChange:internalTextView];
//    [self performSelector:@selector(textViewDidChange:) withObject:internalTextView];
}

-(NSString*)text
{
	return internalTextView.text;
}

-(void)setFont:(UIFont *)afont
{
	internalTextView.font= afont;
	[self setMaximumNumberOfLines:maximumNumberOfLines];
	[self setMinimumNumberOfLines:minimumNumberOfLines];
}

-(UIFont *)font
{
	return internalTextView.font;
}

-(void)setTextColor:(UIColor *)color
{
	internalTextView.textColor = color;
}

-(UIColor*)textColor
{
	return internalTextView.textColor;
}

-(void)setTextAlignment:(NSTextAlignment)aligment
{
	internalTextView.textAlignment = aligment;
}

-(NSTextAlignment)textAlignment
{
	return internalTextView.textAlignment;
}

-(void)setSelectedRange:(NSRange)range
{
	internalTextView.selectedRange = range;
}

-(NSRange)selectedRange
{
	return internalTextView.selectedRange;
}

-(void)setEditable:(BOOL)beditable
{
	internalTextView.editable = beditable;
}

-(BOOL)isEditable
{
	return internalTextView.editable;
}

-(void)setReturnKeyType:(UIReturnKeyType)keyType
{
	internalTextView.returnKeyType = keyType;
}

-(UIReturnKeyType)returnKeyType
{
	return internalTextView.returnKeyType;
}

-(void)setDataDetectorTypes:(UIDataDetectorTypes)datadetector
{
	internalTextView.dataDetectorTypes = datadetector;
}

-(UIDataDetectorTypes)dataDetectorTypes
{
	return internalTextView.dataDetectorTypes;
}

- (BOOL)hasText
{
	return [internalTextView hasText];
}

- (void)scrollRangeToVisible:(NSRange)range
{
	[internalTextView scrollRangeToVisible:range];
}

#pragma mark -
#pragma mark UIExpandingTextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
	if ([delegate respondsToSelector:@selector(expandingTextViewShouldBeginEditing:)])
    {
		return [delegate expandingTextViewShouldBeginEditing:self];
	}
    else
    {
		return YES;
	}
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
	if ([delegate respondsToSelector:@selector(expandingTextViewShouldEndEditing:)])
    {
		return [delegate expandingTextViewShouldEndEditing:self];
	}
    else
    {
		return YES;
	}
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
	if ([delegate respondsToSelector:@selector(expandingTextViewDidBeginEditing:)])
    {
		[delegate expandingTextViewDidBeginEditing:self];
	}
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
	if ([delegate respondsToSelector:@selector(expandingTextViewDidEndEditing:)])
    {
		[delegate expandingTextViewDidEndEditing:self];
	}
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)atext
{
    
	if(![textView hasText] && [atext isEqualToString:@""])
    {
        return NO;
	}
    
	if ([atext isEqualToString:@"\n"])
    {
		if ([delegate respondsToSelector:@selector(expandingTextViewShouldReturn:)])
        {
			if (![delegate performSelector:@selector(expandingTextViewShouldReturn:) withObject:self])
            {
				return YES;
			}
            else
            {
				return NO;
			}
		}
	}
	return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    
	if ([delegate respondsToSelector:@selector(expandingTextViewDidChangeSelection:)])
    {
		[delegate expandingTextViewDidChangeSelection:self];
	}
}

@end
